package src.estore.network;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Scanner;
import src.estore.Product;

public class EStoreClient {
    private String serverAddress;
    private int serverPort;

    public EStoreClient(String address, int port) {
        this.serverAddress = address;
        this.serverPort = port;
    }

    public void browseProducts() {
        Socket socket = null;
        try {
            // 连接服务器
            socket = new Socket(serverAddress, serverPort);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送获取商品列表请求
            output.writeObject("GET_ALL_PRODUCTS");
            output.flush();

            // 读取服务器响应
            List<Product> products = (List<Product>) input.readObject();

            // 打印商品列表
            System.out.println("=== 商品列表 ===");
            for (Product product : products) {
                System.out.println(product);
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 确保关闭socket
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void startClient() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\n=== 电子商城客户端 ===");
            System.out.println("1. 浏览商品");
            System.out.println("2. 退出");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    System.out.println("谢谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    public static void main(String[] args) {
        EStoreClient client = new EStoreClient("localhost", 8888);
        client.startClient();
    }
}
